﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows8Accelerator.Core.Xaml.Html;

namespace Windows8Accelerator.Core.Xaml.Controls.RichText
{
    public abstract class ContentVisitor : SuperHtmlNodeVisitor
    {
        public ContentVisitor(SuperHtmlNode superHtmlNode, SuperHtmlNodeVisitor parentVisitor)
            : base(superHtmlNode, parentVisitor)
        {
        }

        protected sealed override void InternalVisitNode(SuperHtmlNode htmlNode)
        {
            InternalVisitNode1(htmlNode);
            if (Results.Count > 0)
            {
                State.HasContent = true;
                State.AllowLeadingSpace = true;
            }
        }

        protected abstract void InternalVisitNode1(SuperHtmlNode htmlNode);

        protected string Trim(string text)
        {
            if (String.IsNullOrEmpty(text))
                return String.Empty;
            var length = text.Length;
            var sb = new StringBuilder();
            var index = 0;
            var ch = text[index];
            while ((ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t') && index < length - 1)
                ch = text[++index];
            bool hasContent = false;
            while (index < length)
            {
                ch = text[index++];
                if (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')
                {
                    if (hasContent)
                    {
                        sb.Append(' ');
                        hasContent = false;
                    }
                }
                else
                {
                    sb.Append(ch);
                    hasContent = true;
                }
            }
            if ((ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t') && sb.Length > 0)
                sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
    }
}
